/**
 *  自己本地的文件上传
 *  Created by lihao on 2018-04-25
 */

let express = require('express');
let router = express.Router();
let fs = require('fs');
let multiparty = require('multiparty');

// 测试上传页面
router.get('/upload-test', function(req, res, next) {
    res.render('by-upload', { title: 'By' });
});

/* GET 本地测试文件上传. */
router.post('/upload', function(req, res, next) {
    // console.log('body', req.body);
    try {
        //接收前台POST过来的base64
        let imgData = req.body.data;

        //过滤data:URL
        let base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");

        let dataBuffer = new Buffer(base64Data, 'base64');

        fs.writeFile('public/images/'+req.body.name, dataBuffer, function(err) {
            if(err){
                res.send(err);
            }else{
                res.send('保存成功');
            }
        });

    } catch (e) {
        let form = new multiparty.Form({
            uploadDir: 'C:/images/',//路径需要对应自己的项目更改
            /*设置文件保存路径 */
            encoding: 'utf-8',
            /*编码设置 */
            maxFilesSize: 20000 * 1024 * 1024,
            /*设置文件最大值 20MB */
            keepExtensions: true,
            /*保留后缀*/
        });
        form.parse(req, function(err, fields, files){
            if(err){
                res.send({
                    code:10004,
                    success: false,
                    message:err.message,
                    data: {}
                });
            } else {
                console.log('filesName',fields);
                console.log('filesContent',files)
                res.send({
                    code:0,
                    success: false,
                    message: '获取信息成功',
                    data: {
                        name: fields,
                        data: files
                    }
                });
            }
        });
    }
    // res.send('respond with a resource');
});


module.exports = router;
